/**
 * 工作流审核通用JS
 * 非VUE打包生成的代码,请勿删除
 * @author zhangxingju
 */
class WorkflowAudit {

    //静态方法,打开审批页面WorkflowAudit.openAuditPage(ctx, id, taskId);
    static openAuditPage(ctx, id, taskId) {
        $.get(ctx + "/conf/dk/workflow/process/page?taskId=" + taskId, function (res) {
            window.open(ctx + res.data + `?id=${id}&taskId=${taskId}`);
        })
    }

    constructor(options = {}) {
        this.taskId = options.taskId;
        this.instanceId = options.instanceId;
        this.versionId = options.versionId;
        this.displayDiagram = options.displayDiagram || false;
        this.ctx = options.ctx || '';
        this.nextNodes = [];
        this.prevNodes = [];
        this.operations = [];
        // 前置处理回调函数
        this.beforeSubmitCallback = options.beforeSubmitCallback || null;
        this.init();
    }

    init() {
        this.loadOperations();
        this.loadNextNodes();
        this.loadPrevNodes();
    }

    // 加载操作按钮
    loadOperations() {
        const self = this;
        $.get(this.ctx + "conf/dk/workflow/task/operations?taskId=" + this.taskId, function (result) {
            self.operations = result.data || [];
            self.renderOperationButtons();
        });
    }

    // 加载下一节点
    loadNextNodes() {
        const self = this;
        $.get(this.ctx + "conf/dk/workflow/task/next-nodes?taskId=" + this.taskId, function (result) {
            self.nextNodes = result.data || [];
        });
    }

    // 加载上一节点
    loadPrevNodes() {
        const self = this;
        $.get(this.ctx + "conf/dk/workflow/task/prev-nodes?taskId=" + this.taskId, function (result) {
            self.prevNodes = result.data || [];
        });
    }

    // 渲染操作按钮
    renderOperationButtons() {
        const menuBarContent = document.getElementById('menuBarContent');
        if (!menuBarContent) return;

        menuBarContent.innerHTML = '';
        this.operations.forEach(operation => {
            const button = document.createElement('button');
            button.className = 'layui-btn';

            if (operation.value === 'APPROVED') {
                button.className += ' layui-btn-normal';
                button.innerHTML = '<i class="layui-icon layui-icon-ok"></i><span>' + operation.label + '</span>';
            } else if (operation.value === 'DISAPPROVED') {
                button.className += ' layui-btn-danger';
                button.innerHTML = '<i class="layui-icon layui-icon-close"></i><span>' + operation.label + '</span>';
            } else {
                button.innerHTML = '<span>' + operation.label + '</span>';
            }

            button.dataset.action = operation.value;
            button.addEventListener('click', () => this.handleOperationClick(operation));
            menuBarContent.appendChild(button);
        });
    }

    // 处理操作按钮点击
    async handleOperationClick(operation) {
        const opinion = $("#opinion-textarea").val().trim();
        if (!opinion) {
            layer.msg('请填写审核意见', {icon: 2});
            return;
        }

        // 执行前置处理
        if (this.beforeSubmitCallback) {
            try {
                const canContinue = await this.beforeSubmitCallback(operation);
                if (!canContinue) {
                    return;
                }
            } catch (error) {
                console.error('前置处理执行失败:', error);
                return;
            }
        }

        // 根据操作类型处理
        if (operation.value === 'APPROVED' && this.nextNodes.length > 1) {
            this.showNodeSelection(operation, opinion);
        } else if (operation.value === 'RETURN_PREVIOUS' && this.prevNodes.length > 1) {
            this.showNodeSelection(operation, opinion, true);
        } else {
            const nextNodeId = this.nextNodes.length === 1 ? this.nextNodes[0].id : null;
            const prevNodeId = this.prevNodes.length === 1 ? this.prevNodes[0].id : null;
            this.submitData(operation.value, opinion, nextNodeId, prevNodeId);
        }
    }

    // 显示节点选择对话框
    showNodeSelection(operation, opinion, isPrevious = false) {
        const nodes = isPrevious ? this.prevNodes : this.nextNodes;

        // 如果节点数不大于1，直接提交数据
        if (!nodes || nodes.length <= 1) {
            const nodeId = nodes && nodes.length === 1 ? nodes[0].id : null;
            this.submitData(
                operation.value,
                opinion,
                isPrevious ? null : nodeId,
                isPrevious ? nodeId : null
            );
            return;
        }

        const html = `
            <div class="node-selection-dialog" style="padding: 8px;">
                <div class="layui-form-item">
                    <select class="node-select" id="nextNodeSelect">
                        <option value="">系统默认</option>
                        ${nodes.map(node => `<option value="${node.id}">${node.name}</option>`).join('')}
                    </select>
                </div>
            </div>
        `;

        layer.open({
            type: 1,
            title: '选择' + (isPrevious ? '上一' : '下一') + '节点',
            content: html,
            area: ['400px', '180px'],
            btn: ['确定', '取消'],
            btnAlign: 'c',
            success: function (layero) {
                setTimeout(function () {
                    document.querySelector('.node-select').focus();
                }, 100);
            },
            yes: (index) => {
                const nodeId = document.querySelector('.node-select').value;
                this.submitData(
                    operation.value,
                    opinion,
                    isPrevious ? null : nodeId,
                    isPrevious ? nodeId : null
                );
                layer.close(index);
            }
        });
    }

    // 提交数据
    submitData(action, comment, nextNodeId, prevNodeId) {
        const submitData = {
            id: this.taskId,
            action: action,
            businessId: this.instanceId,
            comment: comment,
            nextNodeId: nextNodeId || null,
            prevNodeId: prevNodeId || null,
        };

        // 根据action获取对应的提示语
        let confirmMsg = '确认提交审核意见吗？';
        switch (action) {
            case 'APPROVED':
                confirmMsg = '确认通过吗？';
                break;
            case 'DISAPPROVED':
                confirmMsg = '确认不通过吗？';
                break;
            case 'RETURN_PREVIOUS':
                confirmMsg = '确认退回上一步吗？';
                break;
            case 'RETURN_APPLICANT':
                confirmMsg = '确认退回申请人吗？';
                break;
        }

        // 添加二次确认
        layer.confirm(confirmMsg, {
            title: '操作确认',
            btn: ['确认', '取消']
        }, (index) => {
            layui.layer.close(index);
            $.postJson(this.ctx + "conf/dk/workflow/runtime-tasks/process", submitData, function (result) {
                layui.msg.success("提交成功");
                setTimeout(() => {
                    //window.opener.location.reload()
                    // 发送通讯指令
                    WorkflowAudit.channel.postMessage(WorkflowAudit.channelMessage);
                    window.close();
                }, 1000);
            });
        });
    }

    //获取审核历程的url
    getAuditHistoryUrl() {
        return this.ctx + `static/workflow/index.html#/workflow/instance/detail?instanceId=${this.instanceId}&versionId=${this.versionId}&displayDiagram=${this.displayDiagram}`;
    }
}